import subprocess

class ADBHelper:
    def __init__(self):
        self.start_adb_server()

    def start_adb_server(self):
        try:
            command = ['adb', 'start-server']
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("ADB服务器启动成功:", result.stdout)
        except subprocess.CalledProcessError as e:
            print("ADB服务器启动失败:", e.stderr)

    def check_connected_devices(self):
        try:
            command = ['adb', 'devices']
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("已连接的设备:")
            print(result.stdout)
            return result.stdout
        except subprocess.CalledProcessError as e:
            print("检查设备失败:", e.stderr)
            return None

    def install_apk(self, apk_path, device_serial=None):
        try:
            command = ['adb'] + (['-s', device_serial] if device_serial else []) + ['install', apk_path]
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("安装成功:")
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print("安装失败:")
            print(e.stderr)

    def uninstall_apk(self, package_name, device_serial=None):
        try:
            command = ['adb'] + (['-s', device_serial] if device_serial else []) + ['uninstall', package_name]
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("卸载成功:", result.stdout)
        except subprocess.CalledProcessError as e:
            print("卸载失败:")
            print(e.stderr)


if __name__ == '__main__':
    apk_path = "/Users/wancongpeng/Downloads/apk/douyin.apk"
    package_name = 'com.example.yourapp'
    device_serial = '60.28.168.125:20446'  # 替换为实际设备序列号

    adbhelper = ADBHelper()
    adbhelper.check_connected_devices()
    adbhelper.install_apk(apk_path, device_serial=device_serial)